package com.ljq.intemalcommon.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ljq.intemalcommon.constant.IdentityConstant;
import com.ljq.intemalcommon.dto.TokenResult;
import com.ljq.intemalcommon.responese.TokenResponse;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.mindrot.jbcrypt.BCrypt;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    // 盐
    private static final String  SIGN = "xxx";

    private static final String JWT_KEY_PHONE = "passenger";

    private static final String JWT_KEY_IDENTITY = "identity";

    // 生成token

    public static TokenResponse getToken(String phone, String identity){
        Map<String ,String > map = new HashMap<>();
        map.put(JWT_KEY_PHONE,phone);
        map.put(JWT_KEY_IDENTITY, identity);

        // 设置过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        Date date = calendar.getTime();

        // 创建一个JWT构造器
        JWTCreator.Builder builder = JWT.create();

        // 整合map到jwt构造器中
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            builder.withClaim(key, value);
        }

        // 整合过期时间
        builder.withExpiresAt(date);

        // 生成token
        String token = builder.sign(Algorithm.HMAC256(SIGN));
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setToken(token);
        return tokenResponse;
    }

    // 解析token
    public static TokenResult parseToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).toString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).toString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    public static void main(String[] args){
        TokenResponse token = getToken("17671297357", IdentityConstant.PASSENGER_IDENTITY);
        String token1 = token.getToken();
        System.out.println("token:"+token1);
        System.out.println("手机号:"+parseToken(token1).getPhone());
        System.out.println("身份:"+parseToken(token1).getIdentity());
    }

}
